package com.dd.cloud.user.service.doctor.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.HealthConstants;
import com.dd.cloud.common.constants.IntegralConstants;
import com.dd.cloud.common.constants.SmsConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.*;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.doctor.*;
import com.dd.cloud.user.entity.product.ProductGiveRecord;
import com.dd.cloud.user.entity.product.ProductGiveRule;
import com.dd.cloud.user.mapper.doctor.DoctorDetailApplyMapper;
import com.dd.cloud.user.mq.MQConfig;
import com.dd.cloud.user.mq.RabbitSend;
import com.dd.cloud.user.req.consult.ImUpdateUserReq;
import com.dd.cloud.user.req.doctor.DoctorDetailApplyAuthReq;
import com.dd.cloud.user.req.doctor.DoctorDetailApplyPageReq;
import com.dd.cloud.user.req.doctor.DoctorDetailApplyReviewPageReq;
import com.dd.cloud.user.req.doctor.DoctorDetailApplyReviewReq;
import com.dd.cloud.user.res.doctor.DoctorDetailApplyDetailRes;
import com.dd.cloud.user.res.doctor.DoctorDetailApplyLastTipRes;
import com.dd.cloud.user.res.doctor.DoctorDetailApplyPageRes;
import com.dd.cloud.user.res.doctor.DoctorDetailApplyReviewPageRes;
import com.dd.cloud.user.service.consule.ITencentImMsgService;
import com.dd.cloud.user.service.doctor.*;
import com.dd.cloud.user.service.news.INewsInfoService;
import com.dd.cloud.user.service.product.IProductGiveRecordService;
import com.dd.cloud.user.service.product.IProductGiveRuleService;
import com.dd.cloud.user.vo.DelayMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class DoctorDetailApplyServiceImpl extends ServiceImpl<DoctorDetailApplyMapper, DoctorDetailApply> implements IDoctorDetailApplyService {
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IDoctorDetailService doctorDetailService;
    @Autowired
    private IDoctorDetailReviewService doctorDetailReviewService;
    @Autowired
    private INewsInfoService newsInfoService;
    @Autowired
    private RabbitSend rabbitSend;

    @Autowired
    private IDoctorTaskRecordService doctorTaskRecordService;

    @Value("${reviewPresDoctorId}")
    private Integer reviewPresDoctorId;

    @Autowired
    private IBindReviewPresDoctorService bindReviewPresDoctorService;

    @Autowired
    private IProductGiveRecordService productGiveRecordService;


    /**
     * 医生(认证申请/修改资料/互联网执业备案)提交申请
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDoctorDetailApplyAuth(DoctorDetailApplyAuthReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        if (req.getType() == null) {
            throw new ZekeException(400, "申请类型不能为空");
        }
        DoctorUser du = doctorUserService.getById(loginInfo.getId());
        if (du == null) {
            throw new ZekeException(400, "医生账号异常");
        }
        if (du.getType() == UserConstants.DoctorUserType.PUB_NO_AUTH) {
            throw new ZekeException(400, "该公益账号未开通认证入口,请联系相关人员开通");
        }
        if (req.getType() == 4 && du.getIsPass() == 1) {
            throw new ZekeException(400, "请勿重复备案互联网执业备案");
        }
        QueryWrapper<DoctorDetailApply> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorDetailApply::getDoctorId, loginInfo.getId());
        qw.lambda().eq(DoctorDetailApply::getType, req.getType());
        qw.lambda().eq(DoctorDetailApply::getStatus, UserConstants.DoctorDetailApplyStatus.UN_REVIEW);
        qw.last("limit 1");
        int count = count(qw);
        if (count > 0) {
            throw new ZekeException(400, "已存在待审核认证记录/修改信息记录/互联网备案记录");
        }
        QueryWrapper<DoctorDetail> qws = new QueryWrapper<>();
        qws.lambda().eq(DoctorDetail::getDoctorId, loginInfo.getId());
        DoctorDetailApply dda = new DoctorDetailApply();
        DoctorDetail dd;
        switch (req.getType()) {
            case 1:
                BeanUtils.copyProperties(req, dda);
                ValidatorUtils.verify(req, DoctorDetailApplyAuthReq.class);
                qws.lambda().select(DoctorDetail::getMobileNumber);
                dd = doctorDetailService.getOne(qws);
                dda.setMobileNumber(dd.getMobileNumber());
                dda.setSex(IDCardUtils.getSex(req.getIdCard()));
                dda.setAge(IDCardUtils.getAge(req.getIdCard()));
                dda.setBirthDate(DateUtils.ofLocalDate(IDCardUtils.getBirthday(req.getIdCard())));
                break;
            case 2:
            case 3:
                dd = doctorDetailService.getOne(qws);
                BeanUtils.copyProperties(dd, dda);
                dda.setMechanId(req.getMechanId());
                if (ObjectUtil.isNull(req.getMechanId())) {
                    dda.setMechanId(du.getMechanId());
                }
                dda.setOldMechanId(req.getOldMechanId());
                dda.setOrganization(req.getOrganization());
                dda.setOldOrganization(req.getOldOrganization());
                if (StringUtils.isBlank(dda.getOldOrganization())) {
                    dda.setOldOrganization(dd.getOrganization());
                }
                dda.setGoodAt(req.getGoodAt());
                dda.setOldGoodAt(req.getOldGoodAt());
                if (StringUtils.isBlank(dda.getGoodAt())) {
                    dda.setGoodAt(dd.getGoodAt());
                }
                if (StringUtils.isBlank(dda.getOldGoodAt())) {
                    dda.setOldGoodAt(dd.getGoodAt());
                }
                break;
            case 4:
                dd = doctorDetailService.getOne(qws);
                dd.setId(null);
                if (dd.getQualificationType() != UserConstants.QualificationType.PRACTICE) {
                    throw new ZekeException(400, "执业医师认证的账号才可互联网执业备案");
                }
                QueryWrapper<DoctorDetailApply> qw4 = new QueryWrapper<>();
                qw4.lambda().eq(DoctorDetailApply::getDoctorId, loginInfo.getId());
                qw4.lambda().eq(DoctorDetailApply::getType, 4);
                qw4.lambda().eq(DoctorDetailApply::getStatus, UserConstants.DoctorDetailApplyStatus.SAVE);
                qw4.lambda().select(DoctorDetailApply::getId);
                DoctorDetailApply temp = getOne(qw4);
                BeanUtils.copyProperties(dd, dda);
                dda.setQuaCertificateNo(req.getQuaCertificateNo()).setQuaCertificateDate(req.getQuaCertificateDate()).setQuaCertificatePhoto(req.getQuaCertificatePhoto()).setPraCertificatePhoto(req.getPraCertificatePhoto()).setPraCertificateDate(req.getPraCertificateDate()).setPraCertificateNo(req.getPraCertificateNo()).setOrganization(req.getOrganization()).setTechnicalCategories(req.getTechnicalCategories()).setProfessionalTechnicians(req.getProfessionalTechnicians()).setAttribute(req.getAttribute()).setDoctorType(req.getDoctorType()).setWorkDate(req.getWorkDate()).setPracticeArea(req.getPracticeArea()).setMechanId(du.getMechanId());
                if (req.getIsSave() == 1) {
                    dda.setStatus(UserConstants.DoctorDetailApplyStatus.SAVE);
                } else {
                    dda.setStatus(UserConstants.DoctorDetailApplyStatus.UN_REVIEW);
                }
                if (temp != null) {
                    dda.setId(temp.getId());
                }
                break;
            default:
                throw new ZekeException(400, "未知申请类型");
        }
        dda.setType(req.getType());
        dda.setDoctorId(loginInfo.getId());
        if (dda.getStatus() == null) {
            dda.setStatus(UserConstants.DoctorDetailApplyStatus.UN_REVIEW);
        }
        dda.setCreateDate(LocalDateTime.now());
        saveOrUpdate(dda);
        if (req.getType() == 1) {
            LambdaQueryWrapper<DoctorTaskRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DoctorTaskRecord::getDoctorId, loginInfo.getId())
                    .eq(DoctorTaskRecord::getType, IntegralConstants.IntegralType.TWO_TYPE);
            DoctorTaskRecord doctorTaskRecord = doctorTaskRecordService.getOne(queryWrapper);
            if (doctorTaskRecord == null) {
                doctorTaskRecord.setDoctorId(loginInfo.getId())
                        .setIsShow(1)
                        .setStatus(1)
                        .setType(IntegralConstants.IntegralType.TWO_TYPE)
                        .setCreateDate(LocalDateTime.now());
                Boolean flag = doctorTaskRecordService.save(doctorTaskRecord);
                if (!flag) {
                    log.info("资质认证任务提交申请失败");
                    return;
                }
            } else {
                doctorTaskRecord.setCreateDate(LocalDateTime.now());
                doctorTaskRecordService.updateById(doctorTaskRecord);
            }
            DelayMqVo<Integer> delayMqVo = new DelayMqVo<>();
            delayMqVo.setT(doctorTaskRecord.getId());
            delayMqVo.setType(DelayMqVo.DelayMqVoType.DOCTOR_TASK);
            //毫秒级 当前时间距离24点时间差
            long ms = DateUtils.nowUtilEndDate();
            rabbitSend.sendMessageDelay(MQConfig.DELAY_EXCHANGE, MQConfig.DELAY_KEY, delayMqVo, ms);
        }
    }

    /**
     * 查询医生最后一次(认证申请/修改资料/互联网执业备案)信息状态
     * 医生id不传默认当前登录医生id
     *
     * @param docId
     * @param type
     * @return
     */
    @Override
    public Map<String, Integer> getDoctorDetailApplyLastStatus(Integer docId, Integer type) {
        if (docId == null) {
            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
            docId = loginInfo.getId();
        }
        QueryWrapper<DoctorDetailApply> qw = new QueryWrapper<>();
        qw.lambda().eq(DoctorDetailApply::getDoctorId, docId);
        if (type != null) {
            qw.lambda().eq(DoctorDetailApply::getType, type);
        }
        qw.lambda().orderByDesc(DoctorDetailApply::getCreateDate);
        qw.last("limit 1");
        DoctorDetailApply dda = getOne(qw);
        if (dda == null) {
            return null;
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("id", dda.getId());
        map.put("type", dda.getType());
        map.put("status", dda.getStatus());
        return map;
    }

    /**
     * 查询医生最后一次(认证申请/修改资料/互联网备案)审核提示
     *
     * @param docId
     * @param type
     * @return
     */
    @Override
    public DoctorDetailApplyLastTipRes getDoctorDetailApplyLastTip(Integer docId, Integer type, HttpServletRequest request) {
        String client = request.getHeader("client");
        Integer pcTipCount = 0;
        if (HealthConstants.ClientType.HEALTHPC.equals(client)) {
            pcTipCount = 1;
        }
        if (docId == null) {
            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
            docId = loginInfo.getId();
        }
        DoctorDetailApplyLastTipRes res = getBaseMapper().getDoctorDetailApplyLastTip(docId, type);
        if (res == null || res.getStatus() == UserConstants.DoctorDetailApplyStatus.UN_REVIEW || res.getStatus() == UserConstants.DoctorDetailApplyStatus.SAVE) {
            return null;
        }
        if (res.getTipCount() == 0) {
            doctorDetailReviewService.addDoctorDetailReviewTipCount(res.getReviewId(), res.getTipCount(), pcTipCount);
            res.setIsTip(1);
        } else {
            if (res.getType() == 1 && res.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW_FA_IL) {
                doctorDetailReviewService.addDoctorDetailReviewTipCount(res.getReviewId(), res.getTipCount(), pcTipCount);
                res.setIsTip(1);
            }
        }
        return res;
    }

    /**
     * 查询医生最后一次(认证申请/修改资料/互联网执业备案)信息记录
     * 医生id不传默认当前登录医生id
     *
     * @param docId
     * @param type
     * @return
     */
    @Override
    public DoctorDetailApplyDetailRes getDoctorDetailApplyDetailLast(Integer docId, Integer type) {
        if (docId == null) {
            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
            docId = loginInfo.getId();
        }
        type = type == null ? 4 : type;
        return getBaseMapper().getDoctorDetailApplyDetailLast(docId, type);
    }

    @Autowired
    private ITencentImMsgService tencentImMsgService;

    @Autowired
    private IDoctorPresenterNumService doctorPresenterNumService;

    @Autowired
    private IDoctorEquityService doctorEquityService;

    @Autowired
    private IProductGiveRuleService productGiveRuleService;

    /**
     * 医生(认证申请/修改资料/互联网备案) 审核
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doctorDetailApplyReview(DoctorDetailApplyReviewReq req) {
        if (req.getStatus() != UserConstants.DoctorDetailApplyStatus.REVIEW && req.getStatus() != UserConstants.DoctorDetailApplyStatus.REVIEW_FA_IL) {
            throw new ZekeException(400, "状态参数错误");
        }
        DoctorDetailApply dda = getById(req.getApplyId());
        if (dda == null) {
            throw new ZekeException(400, "认证/信息修改记录不存在");
        }
        if (dda.getStatus() != UserConstants.DoctorDetailApplyStatus.UN_REVIEW) {
            throw new ZekeException(400, "请勿重复审核");
        }
        DoctorDetailApply update = new DoctorDetailApply();
        if (req.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW) {
            DoctorDetail doctorDetail = null;
            DoctorDetail dd = new DoctorDetail();
            DoctorUser du = new DoctorUser();
            dd.setDoctorId(dda.getDoctorId());
            if (dda.getType() == 1) {
                BeanUtils.copyProperties(dda, dd);
                dd.setProCertificate(req.getProCertificate());
                dd.setQuaCertificateNo(req.getQuaCertificateNo());
                dd.setQuaCertificateDate(req.getQuaCertificateDate());
                dd.setPraCertificateNo(req.getPraCertificateNo());
                dd.setPraCertificateDate(req.getPraCertificateDate());
                du.setId(dda.getDoctorId());
                du.setStatus(UserConstants.DoctorUserStatus.NORMAL);
                if (req.getMechanId() == null) {
                    throw new ZekeException(400, "管理机构id不能为空!");
                }
                du.setMechanId(req.getMechanId());
                du.setAuthDate(LocalDateTime.now());
                update.setMechanId(req.getMechanId());
                if (ObjectUtils.equalsAndNotNull(dda.getQualificationType(), UserConstants.QualificationType.COUNTRY)) {
                    if (UserConstants.CertificateType.NOT_HAVE_PRES_POWER.contains(dda.getCertificateType().toString())) {
                        du.setIsPresPower(0);
                    } else {
                        du.setIsPresPower(1);
                    }
                    if (ObjectUtils.equalsAndNotNull(dda.getCertificateType(), UserConstants.CertificateType.ONE)) {
                        du.setAuthType(UserConstants.DoctorUserAuthType.VILLAGE);
                    }
                } else {
                    du.setIsPresPower(1);
                }
                if (!StringUtils.isBlank(dda.getHealthCommitteePhoto())) {
                    if (StringUtils.isBlank(dda.getQuaCertificateNo()) || dda.getQuaCertificateDate() == null || StringUtils.isBlank(dda.getPraCertificateNo()) || StringUtils.isBlank(dda.getPraCertificatePhoto())) {
                        du.setAuthType(UserConstants.DoctorUserAuthType.NOT_HAVE_INFO);
                    }
                }
                du.setIsCertification(UserConstants.IsCertification.certification);
            } else if (dda.getType() == 2) {
                dd.setGoodAt(dda.getGoodAt());
            } else if (dda.getType() == 3) {
                dd.setOrganization(dda.getOrganization());
                du.setId(dda.getDoctorId());
                if (req.getMechanId() == null) {
                    throw new ZekeException("管理机构id不能为空!");
                }
                du.setMechanId(req.getMechanId());
                update.setMechanId(req.getMechanId());
            } else if (dda.getType() == 4) {
                dd.setQuaCertificatePhoto(dda.getQuaCertificatePhoto()).setWorkDate(dda.getWorkDate()).setPracticeArea(dda.getPracticeArea()).setProfessionalTechnicians(dda.getProfessionalTechnicians()).setTechnicalCategories(dda.getTechnicalCategories()).setDoctorType(dda.getDoctorType()).setAttribute(dda.getAttribute()).setPraCertificateDate(dda.getPraCertificateDate()).setProCertificatePhoto(dda.getProCertificatePhoto()).setQuaCertificateNo(dda.getQuaCertificateNo()).setQuaCertificateDate(dda.getQuaCertificateDate()).setPraCertificateNo(dda.getPraCertificateNo()).setPraCertificatePhoto(dda.getPraCertificatePhoto()).setDoctorId(dda.getDoctorId());
                du.setId(dda.getDoctorId());
                if (req.getMechanId() == null) {
                    throw new ZekeException("管理机构id不能为空!");
                }
                du.setMechanId(req.getMechanId());
                du.setIsPass(1);
                du.setPushStatus(0);
            } else if (dda.getType() == 5) {
                LambdaQueryWrapper<DoctorDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DoctorDetail::getDoctorId, dda.getDoctorId());
                doctorDetail = doctorDetailService.getOne(queryWrapper);
                BeanUtils.copyProperties(dda, dd);
                dd.setStatus(doctorDetail.getStatus()).setCreateDate(doctorDetail.getCreateDate());
                du.setId(dda.getDoctorId());
                if (req.getMechanId() == null) {
                    throw new ZekeException("管理机构id不能为空!");
                }
                du.setMechanId(req.getMechanId());
            }
            doctorDetailService.updateDoctorDetail(dd);
            doctorUserService.updateDoctorUser(du);
            if (dda.getType() == 5 && doctorDetail != null) {
                String oldName = doctorDetail.getName();
                String oldAvatar = doctorDetail.getAvatar() == null ? "" : doctorDetail.getAvatar();
                String newAvatar = dda.getAvatar() == null ? "" : dda.getAvatar();
                String newName = dda.getName();
                if (!newName.equals(oldName) || !newAvatar.equals(oldAvatar)) {
                    log.info("姓名字:{},老名字:{},头像:{},{}", newName, oldName, newAvatar, oldAvatar);
                    log.info("审核发送im消息----修改医生头像及医生名字");
                    ImUpdateUserReq imUpdateUserReq = new ImUpdateUserReq();
                    imUpdateUserReq.setUserName(newName);
                    imUpdateUserReq.setUserType(1);
                    imUpdateUserReq.setUserId(dda.getDoctorId());
                    imUpdateUserReq.setFaceUrl(dda.getAvatar());
                    tencentImMsgService.imUpdateImUser(imUpdateUserReq);
                }
            }
            Integer accountType = doctorUserService.getDoctorUserType(dda.getDoctorId());
            if (accountType == 1) {
                doctorUserService.savePresenterNum(1, 2, dda.getDoctorId());
                //注册赠送次数失效
                LambdaUpdateWrapper<ProductGiveRecord> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(ProductGiveRecord::getDoctorId, du.getId())
                        .eq(ProductGiveRecord::getIsAuth, 0)
                        .set(ProductGiveRecord::getStatus, 4);
                Boolean flag2 = productGiveRecordService.update(updateWrapper);
                if (!flag2) {
                    log.info("更新失效");
                }
            }
            if (accountType == 2) {
                saveDoctorEquity(dda.getDoctorId());
            }
        }
        update.setId(req.getApplyId());
        update.setStatus(req.getStatus());
        update.setProCertificate(req.getProCertificate());
        update.setUpdateDate(LocalDateTime.now());
        updateById(update);
        doctorDetailReviewService.addDoctorDetailReview(req);
        //更新医生任务状态
        LambdaQueryWrapper<DoctorTaskRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DoctorTaskRecord::getDoctorId, dda.getDoctorId())
                .eq(DoctorTaskRecord::getType, IntegralConstants.IntegralType.TWO_TYPE)
                .eq(DoctorTaskRecord::getStatus, 1)
                .last("limit 1");
        DoctorTaskRecord doctorTaskRecord = doctorTaskRecordService.getOne(queryWrapper);
        if (dda.getType() == 4) {
            newsInfoService.sendDoctorHlwFilingNoticeReviewNotice(dda.getDoctorId(), dda.getId(), req.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW ? 1 : 2);
        }
        if (dda.getType() == 1 && req.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW) {
            sendShortMessage(dda.getDoctorId(), 1);
            //认证通过发放积分
            String params = IntegralConstants.IntegralType.TWO_TYPE + "-" + dda.getDoctorId();
            log.info("医生认证通过,参数:{}", params);
            rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params);
            DoctorUser doctorUser = doctorUserService.getById(dda.getDoctorId());
            String doctorUserCodeRecord = doctorUser.getCodeRecord();
            Integer type = doctorUser.getInviteType();
            if (StringUtils.isNotBlank(doctorUserCodeRecord) && type != null && doctorUser.getInviteDocId() != null) {
                if (doctorUserCodeRecord.indexOf(HealthConstants.InviteCodePrefixConstants.DOCTOR_PREFIX) == 0 && type == 1) {
                    //认证通过发放积分
                    String params2 = IntegralConstants.IntegralType.FIVE_TYPE + "-" + doctorUser.getInviteDocId();
                    log.info("邀请的医生认证通过,参数:{}", params2);
                    rabbitSend.sendMessage(MQConfig.INTEGRAL_EXCHANGE, MQConfig.INTEGRAL_QUEUE, params2);
                }
            }
            if (doctorTaskRecord != null) {
                doctorTaskRecord.setIsShow(0);
                doctorTaskRecordService.updateById(doctorTaskRecord);
            }
            //学生,爱好者无处方权直接默认签约医生
            if (dda.getQualificationType() == UserConstants.QualificationType.STUDENT
                    || dda.getQualificationType() == UserConstants.QualificationType.PHARMACISTS
                    || dda.getQualificationType() == UserConstants.QualificationType.FAN) {
                BindReviewPresDoctor bindReviewPresDoctor = new BindReviewPresDoctor();
                bindReviewPresDoctor.setApplyDoctorId(dda.getDoctorId())
                        .setReviewDoctorId(reviewPresDoctorId)
                        .setStatus(1)
                        .setCreateDate(LocalDateTime.now())
                        .setUpdateDate(LocalDateTime.now())
                        .setTermEndDate(LocalDate.now().plusYears(1))
                        .setTermStartDate(LocalDate.now());
                Boolean flag = bindReviewPresDoctorService.save(bindReviewPresDoctor);
                if (!flag) {
                    throw new ZekeException("自动签约审方医生失败!");
                }

            }
        } else if (dda.getType() == 1 && req.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW_FA_IL) {
            sendShortMessage(dda.getDoctorId(), 2);
            if (doctorTaskRecord != null) {
                LambdaUpdateWrapper<DoctorTaskRecord> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(DoctorTaskRecord::getStatus, -1)
                        .eq(DoctorTaskRecord::getId, doctorTaskRecord.getId());
                doctorTaskRecordService.update(updateWrapper);
            }
//            DoctorDetailApplyLastTipRes doctorDetailApplyDetailRes = getBaseMapper().getDoctorDetailApplyLastTip(dda.getDoctorId(), 1);
//            if (doctorDetailApplyDetailRes != null) {
//                Integer reviewId = doctorDetailApplyDetailRes.getReviewId();
//                if (reviewId != null) {
//                    LambdaUpdateWrapper<DoctorDetailReview> updateWrapper = new LambdaUpdateWrapper<>();
//                    updateWrapper.set(DoctorDetailReview::getPcTipCount, 0)
//                            .eq(DoctorDetailReview::getId, reviewId);
//                    doctorDetailReviewService.update(updateWrapper);
//                }
//            }
        }
    }


    private void saveDoctorEquity(Integer doctorId) {
        LambdaQueryWrapper<ProductGiveRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductGiveRule::getAccountType, 2)
                .eq(ProductGiveRule::getStatus, 1)
                .eq(ProductGiveRule::getNumType, 2)
                .eq(ProductGiveRule::getType, 1);
        ProductGiveRule productGiveRule = productGiveRuleService.getOne(queryWrapper);
        if (productGiveRule != null) {
            DoctorEquity doctorEquity = new DoctorEquity();
            doctorEquity.setDoctorId(doctorId)
                    .setCreateDate(LocalDateTime.now())
                    .setExperienceDays(productGiveRule.getNum())
                    .setType(2)
                    .setEndDate(LocalDateTime.now().plusDays(productGiveRule.getNum()))
                    .setAccumulateDay(productGiveRule.getNum())
                    .setFirstMonth(0)
                    .setStartDate(LocalDateTime.now())
                    .setExpirDate(LocalDateTime.now().plusDays(productGiveRule.getNum()));
            Boolean flag = doctorEquityService.save(doctorEquity);
            if (!flag) {
                throw new ZekeException("保存失败");
            }
        }
    }

    public void sendShortMessage(Integer doctorId, Integer type) {
        LambdaQueryWrapper<DoctorDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorDetail::getDoctorId, doctorId);
        DoctorDetail doctorDetail = doctorDetailService.getOne(wrapper);
        if (doctorDetail != null && StringUtils.isNotBlank(doctorDetail.getName()) && StringUtils.isNotBlank(doctorDetail.getMobileNumber())) {
            Map<String, String> msg = new HashMap<>(4);
            msg.put("phone", doctorDetail.getMobileNumber());
            msg.put("name", doctorDetail.getName());
            msg.put("param_type", SmsConstants.ParamType.JSON);
            if (type == 1) {
                msg.put("sms_template", SmsConstants.Template.APPLY_PASS);
            } else if (type == 2) {
                msg.put("sms_template", SmsConstants.Template.APPLY_FAIL);
            }
            rabbitSend.sendMessage(MQConfig.SMS_EXCHANGE, MQConfig.SMS_KEY, msg);
            log.info("--------开始发送短信-----------");
        }
    }


    /**
     * 查询医生认证/信息修改申请记录 分页
     *
     * @param req
     * @return
     */
    @Override
    public IPage<DoctorDetailApplyPageRes> queryDoctorDetailApplyPage(DoctorDetailApplyPageReq req) {
        Assert.verifyStatusIdsParam(req.getClass(), req);
        req.setFlag(req.getFlag() == null ? 1 : req.getFlag());
        if (StringUtils.isBlank(req.getType())) {
            req.setType(req.getFlag() == 1 ? "1" : "2,3,5");
        }
        if (StringUtils.isBlank(req.getOrderSort())) {
            req.setOrderSort("asc");
        }
        IPage<DoctorDetailApplyPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryDoctorDetailApplyPage(iPage, req);
        return iPage;
    }

    /**
     * 查询医生认证/信息修改审核记录 分页
     *
     * @param req
     * @return
     */
    @Override
    public IPage<DoctorDetailApplyReviewPageRes> queryDoctorDetailApplyReviewPage(DoctorDetailApplyReviewPageReq req) {
        Assert.verifyStatusIdsParam(req.getClass(), req);
        if (StringUtils.isBlank(req.getOrderSort())) {
            req.setOrderSort("desc");
        }
        IPage<DoctorDetailApplyReviewPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryDoctorDetailApplyReviewPage(iPage, req);
        return iPage;
    }

    /**
     * 查询医生认证/信息修改申请记录详情
     *
     * @param applyId
     * @return
     */
    @Override
    public DoctorDetailApplyDetailRes queryDoctorDetailApplyDetailRes(Integer applyId) {
        return getBaseMapper().queryDoctorDetailApplyDetailRes(applyId);
    }

//    @Override
//    public DoctorDetailApplyLastTipRes getPcDoctorDetailApplyLastTip(Integer docId, Integer type) {
//        if (docId == null) {
//            LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
//            docId = loginInfo.getId();
//        }
//        DoctorDetailApplyLastTipRes res = getBaseMapper().getDoctorDetailApplyLastTip(docId, type);
//        if (res == null || res.getStatus() == UserConstants.DoctorDetailApplyStatus.UN_REVIEW || res.getStatus() == UserConstants.DoctorDetailApplyStatus.SAVE) {
//            return null;
//        }
//        if (res.getTipCount() == 0) {
//            if (res.getPcTipCount() == 0) {
//                res.setPcIsTip(1);
//            }
//            doctorDetailReviewService.addDoctorDetailReviewTipCount(res.getReviewId(), res.getTipCount(),res.getPcTipCount());
//            res.setIsTip(1);
//        } else {
//            if (res.getType() == 1 && res.getStatus() == UserConstants.DoctorDetailApplyStatus.REVIEW_FA_IL) {
//                doctorDetailReviewService.addDoctorDetailReviewTipCount(res.getReviewId(), res.getTipCount());
//                res.setIsTip(1);
//            }
//        }
//
//        return res;
//    }
}
